package info.fastpace.utils.iterator;

import java.util.Iterator;

public abstract class SplitIterator<Root, E> extends ConsecutiveIterator<E> {
	
	private boolean finished = false;
	private Iterator<Root> iterator;

	public SplitIterator(Iterator<Root> iterator) {
		this.iterator = iterator;
	}

	@Override
	public boolean hasNext() {
		if (super.hasNext()) {
			return true;
		}
		if (finished) {
			return false;
		}
		
		while (iterator.hasNext()) {
			Root next = iterator.next();
			Iterator<E> iterator = split(next);
			if (iterator == null || !iterator.hasNext()) {
				continue;
			}else {
				add(iterator);
				return super.hasNext();
			}
		}
		finished = true;
		return false;
	}

	/**
	 * Can return null or an empty iterator to indicate an element that was split to nothing.
	 * 
	 * @param next
	 * @return
	 */
	protected abstract Iterator<E> split(Root root);

	@Override
	public void remove() {
		throw new UnsupportedOperationException("Remove method not supported");
	}

}
